import { computed, ref } from "vue";
import { TabPageContext, UseOnePage, UseTabs } from "../composition/types";
import { TabPageProps } from "./tab-page.props";
import { TabsProps } from "../tabs.props";

export default function (
    tabsProps: TabsProps,
    props: TabPageProps,
    tabPage: TabPageContext,
    useOnePageComposition: UseOnePage,
    useTabsComposition: UseTabs
) {
    const { activeId, removeTab, selectTab } = useTabsComposition;

    const tabTextClass = computed(() => {
        const classObject = {
            'st-tab-text': true,
            'farris-title-auto': tabsProps.autoTitleWidth
        } as Record<string, boolean>;
        return classObject;
    });

    const tabHeaderItemClass = computed(() => {
        const classObject = {
            'nav-item': true,
            'd-none': props.show !== undefined ? !props.show : false,
            'f-state-active': props.id === activeId.value,
            'f-state-disable': props.disabled
        } as Record<string, boolean>;
        return classObject;
    });

    const tabHeaderItemStyle = computed(() => {
        const styleObject = {
            width: `${props.tabWidth}px`
        } as Record<string, any>;
        return styleObject;
    });

    const tabHeaderItemLinkClass = computed(() => {
        const classObject = {
            'nav-link': true,
            'tabs-text-truncate': true,
            'active': props.id === activeId.value,
            'disabled': props.disabled
        } as Record<string, boolean>;
        return classObject;
    });

    function tabTitleRender(tabPageProps: TabPageProps) {
        return <span class={tabTextClass.value} title={tabPageProps.title}>
            {tabPageProps.title}
        </span>;
    }

    function getTabTitleRender(tabPage: TabPageContext) {
        return tabPage.slots.title ? tabPage.slots.title : tabTitleRender;
    }

    const renderTabTitle = getTabTitleRender(tabPage);

    const shouldShowCloseButton = ref(props.removeable);

    function renderCloseButton() {
        return <span class="st-drop-close" onClick={($event) => removeTab($event, props.id)}>
            <i class="f-icon f-icon-close"></i>
        </span>;
    }

    function onClick($event: MouseEvent) {
        selectTab(props.id);
        if (tabsProps.tabType === 'one-page') {
            useOnePageComposition.scrollToByPaggId(props.id);
        }
    }

    return (
        <li class={tabHeaderItemClass.value} style={tabHeaderItemStyle.value}>
            <a class={tabHeaderItemLinkClass.value} onClick={onClick}>
                {renderTabTitle(props)}
                {shouldShowCloseButton.value && renderCloseButton()}
            </a>
        </li>
    );
}
